package com.scproject.scbef.service.study.studyresource.impl;

import com.scproject.dto.ResponseDto;
import com.scproject.scbef.exception.ProcessException;
import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.mapper.ImgRelationMapper;
import com.scproject.scbef.mapper.StudyResourceMapper;
import com.scproject.scbef.pojo.Img;
import com.scproject.scbef.pojo.ImgRelation;
import com.scproject.scbef.pojo.StudyResource;
import com.scproject.scbef.pojo.StudyResourceExample;
import com.scproject.scbef.pojo.expandenum.ImgTypeEnum;
import com.scproject.scbef.pojo.vo.ResponseCodeEnum;
import com.scproject.scbef.service.study.studyresource.StudyResourceService;
import com.scproject.utils.FtpFileUtil;
import com.scproject.utils.JWTUtils;
import com.scproject.utils.ProcessFileUtils;
import com.scproject.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.scproject.utils.ProcessFileUtils.processFile;

/**
 * @author LNL
 * @date 2021/5/24 15:33
 */
@Service("studyResourceService")
public class StudyResourceServiceImpl implements StudyResourceService {

    @Autowired
    private StudyResourceMapper studyResourceMapper;
    @Autowired
    private ImgMapper imgMapper;
    @Autowired
    private ImgRelationMapper imgRelationMapper;


    @Override
    public ResponseDto getAllStudyResources() {
        ResponseDto responseDto = null;
        List<StudyResource> studyResources = studyResourceMapper.selectByExampleWithBLOBs(new StudyResourceExample());
        Optional<List<StudyResource>> optionalList = Optional.ofNullable(studyResources);
        if(optionalList.isPresent()) {
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"学习资料",studyResources);
        }else{
            responseDto = new ResponseDto(ResponseCodeEnum.ERROR.toString(),"获取失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto insertStudyResource(MultipartHttpServletRequest request) {
        ResponseDto responseDto = null;
        Map<String, String> processFile = null;
        //先处理普通字段
        try {
            //获取所有的普通字段
            Map<String, String[]> dataInfo = request.getParameterMap();
            //获取当前处理人
            Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            StudyResource studyResource = new StudyResource();
            studyResource.setId(UUIDUtils.getUUID());
            studyResource.setContent(dataInfo.get("content")[0]);
            studyResource.setTitle(dataInfo.get("title")[0]);
            studyResource.setPublishTime(sdf.parse(dataInfo.get("publishTime")[0]));
            studyResource.setCreateUser(userInfo.get("userId"));
            studyResource.setCreateTime(new Date());

            //添加到数据库
            int isInsert = studyResourceMapper.insertSelective(studyResource);
            if(isInsert > 0) {
                List<MultipartFile> files = request.getFiles("file_transfer");
                for (MultipartFile file : files) {
                    Map<String, String> fileData = ProcessFileUtils.processFile(file);
                    //将图片存放到数据库中
                    Img img = new Img();
                    img.setId(UUIDUtils.getUUID());
                    img.setName(fileData.get("fileName"));
                    img.setPath(fileData.get("filePath"));

                    ImgRelation imgRelation = new ImgRelation();
                    imgRelation.setId(UUIDUtils.getUUID());
                    imgRelation.setImgId(img.getId());
                    imgRelation.setRelationId(studyResource.getId());
                    imgRelation.setType(ImgTypeEnum.STUDY_RESOURCE.toString());

                    //添加资源信息
                    int isInsertImg = imgMapper.insertSelective(img);
                    int isInsertImgRelation = imgRelationMapper.insertSelective(imgRelation);
                    if (isInsertImg > 0 && isInsertImgRelation > 0) {
                        responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"上传成功");
                    } else {
                        throw new ProcessException("添加失败");
                    }
                }
            }else {
                throw new ProcessException("上传失败");
            }
        } catch (Exception e) {
            throw new ProcessException("上传失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto deleteStudyResource(String id) {
        ResponseDto responseDto = null;
        int isDelete = studyResourceMapper.deleteByPrimaryKey(id);
        if(isDelete > 0) {
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"删除成功");
        }else {
            responseDto = new ResponseDto(ResponseCodeEnum.ERROR.toString(),"删除失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto updateStudyResource(MultipartHttpServletRequest request) {

        ResponseDto responseDto = null;
        //先处理普通字段
        try {
            //获取所有的普通字段
            Map<String, String[]> dataInfo = request.getParameterMap();
            //获取当前处理人
            Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            StudyResource newStudyResource = new StudyResource();
            newStudyResource.setId(dataInfo.get("id")[0]);
            newStudyResource.setContent(dataInfo.get("content")[0]);
            newStudyResource.setTitle(dataInfo.get("title")[0]);
            try{
                newStudyResource.setPublishTime(sdf.parse(dataInfo.get("publishTime")[0]));
            } catch (Exception e) {
                throw new ProcessException("日期格式问题，请“以年-月-日”的形式");
            }
            newStudyResource.setEditUser(userInfo.get("userId"));
            newStudyResource.setEditTime(new Date());

            //处理文件
            String uploadVideo = FtpFileUtil.uploadVideo(request);
            if("".equals(uploadVideo)) {
                StudyResource oldStudyResource = studyResourceMapper.selectByPrimaryKey(newStudyResource.getId());
                newStudyResource.setVideoPath(uploadVideo);
            }
            //更新数据库
            int isInsert = studyResourceMapper.updateByPrimaryKeySelective(newStudyResource);
            if(isInsert > 0) {
                responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"更新成功");
            }else {
                throw new ProcessException("更新失败");
            }
        } catch (Exception e) {
            throw new ProcessException("更新失败");
        }
        return responseDto;
    }
}
